package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

/*
查询参数
*/
func handleRequestHead1() gin.HandlerFunc{
	return func(c *gin.Context) {

	}
}


/*
查询参数
*/
func handleRequestHead2() gin.HandlerFunc{
	return func(c *gin.Context) {

	}
}

/*
动态参数
*/
func handleRequestHead3() gin.HandlerFunc{
	return func(c *gin.Context) {

	}
}


/*
表单参数
*/
func handleRequestHead4() gin.HandlerFunc{
	return func(c *gin.Context) {

	}
}


/*
原始参数
*/
func handleRequestHead5() gin.HandlerFunc{
	return func(c *gin.Context) {

	}
}


/*
参数绑定
*/
func handleRequestHead6() gin.HandlerFunc{
	return func(c *gin.Context) {

	}
}


/*
请求头
*/
func handleRequestHead() gin.HandlerFunc{
	return func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"1": c.GetHeader("User-Agent"),
			"2": c.Request.Header.Get("User-Agent"),
			"3": c.Request.Header["User-Agent"],
			"4": c.Request.Header["user-agent"],
		})
	}
}

/*
设置响应头
*/
func handleSetResponseHeader() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Token", "abcdefg")
		c.Header("Content-Type", "application/text;charset=utf-8")
		c.JSON(0, gin.H{"data":"看看响应头"})

	}
}

/*
/user/:id
*/
func handleParam1() gin.HandlerFunc {
	return func(c *gin.Context) {
		id := c.Param("id")
		c.JSON(http.StatusOK, gin.H{"id": id})
	}
}

/*
/user?name=zhang3&age=12
*/

func handleQuery() gin.HandlerFunc {
	return func(c *gin.Context) {
		name := c.Query("name")
		age := c.Query("age")
		c.JSON(http.StatusOK, gin.H{"name":name, "age": age})
	}
}

/*
获取客户的IP
*/
func handleGetClientIp() gin.HandlerFunc {
	return func(c *gin.Context) {
		ip := c.ClientIP()
		c.JSON(http.StatusOK, gin.H{"id": ip})
	}
}

/*
xxxx
*/
func handleX() gin.HandlerFunc {
	return func(c *gin.Context) {

	}
}

/*
文件上传
*/
func handleFileUpload() gin.HandlerFunc {
	return func(c *gin.Context) {
		file, _ := c.FormFile("file")
		_ = c.SaveUploadedFile(file, "./files/1.txt")
		c.JSON(http.StatusOK, gin.H{"other": "other"})
	}
}

/*
多文件处理
*/
func handleManyFileHandle() gin.HandlerFunc {
	return func(c *gin.Context) {
		form, _ := c.MultipartForm()
		files := form.File["file[]"]
		for _, file := range files{
			c.SaveUploadedFile(file, "./files/" + file.Filename)
		}
		c.JSON(http.StatusOK, gin.H{
			"msg": fmt.Sprintf("成功上传%d个文件", len(files)),
		})
	}
}

/*
重定向
*/

func handleRedirect() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
	}
}


func main() {
	r := gin.Default()

	r.GET("/user/:id", handleParam1())
	r.GET("/user", handleQuery())
	r.GET("/ip", handleGetClientIp())
	r.POST("/upload", handleFileUpload())
	r.POST("/uploads", handleManyFileHandle())
	r.GET("/response", handleSetResponseHeader())

	r.Run(":8888")
}
